import Vue from "vue";
import "./extend";
import helper from "./helper/index";
import file from "./file";
import "./http";
import vueExt from "./vue-ext";

const $vue = Vue.prototype;

helper.onAuthFail = (msg = "无保存相册权限") => {
  helper
    .confirm(msg, {
      confirmText: "去设置",
    })
    .then(() => {
      helper.openSetting();
    });
};
$vue.$h = helper;
uni.$h = helper;

for (const fn in vueExt) {
  $vue["$" + fn] = vueExt[fn];
}

uni.$file = file;

// https://uniapp.dcloud.io/api/README?id=路由
export const navTo = (url, act = "navigateTo", params = {}) => {
  if (typeof act == "object" && act) {
    params = act;
    act = "navigateTo";
  }
  if (/^http/.test(url)) {
    params.src = url;
    url = "/pages/webview/webview";
  } else if (/^[a-z]/.test(url) && !url.includes("plugin:")) {
    if (/\//.test(url)) url = `/pages/${url}`;
    else url = `/pages/${url}/${url}`;
  }

  for (const key in params) {
    let val = params[key];
    if (val === undefined) continue;
    if (val && typeof val == "object") val = JSON.stringify(val);
    if (val) val = encodeURIComponent(val);
    const add = /\?/.test(url) ? "&" : "?";
    url += `${add}${key}=${val}`;
  }
  uni[act]({
    url,
  });
};
$vue.$navTo = navTo;
uni.$navTo = navTo;

const navTypes = ["redirectTo", "reLaunch", "switchTab"];
navTypes.forEach((act) => {
  $vue["$" + act] = (url, params) => {
    navTo(url, act, params);
  };
});

$vue.$navBack = () => {
  if (getCurrentPages().length == 1) navTo("index", "reLaunch");
  else uni.navigateBack();
};
